# -*- coding: utf-8 -*-
from google.appengine.api import mail

import models.shippingOrder
import models.trackingInfo as TIM
import models.milestonePlan as MPm
import models.user as UM
import models.option as om
import models.status as sm
from models.enhancedModel import EnhancedModel as EM

def getAuthorityEmail ( so ):
  supervisor = EM.queryLatest( UM.UserModel, so.supervisor ).get()
  return supervisor.account.email()

def getClientsEmail ( so ):
  sender = EM.queryLatest( UserModel, so.sender).get()
  recipient = EM.queryLatest( UserModel, so.recipient).get()
  return [ sender.account.email(), recipient.account.email() ]

def sendOrderReport ( so, sendToClients = False):
  lastTrackingInfos = int(EM.queryLatest(om.OptionModel).filter('name =', "maxMailTIs").get().value)
  mp = EM.queryLatest ( MPm.MPModel, so.mp ).get()
  
  msgBodyTemplate = '''
  Dear %s
  
  There are some problems with order n. %d...
  
  It is currently %d hrs delayed.
  
  Below are last %d tracking informations reported for this order:
  '''
  trackingInfos = EM.queryLatest ( TIM.TIModel ).filter( 'shippingOrder =', so.ident ).fetch( lastTrackingInfos )
  
  for (i, info) in enumerate( trackingInfos ):
    status = sm.StatusModel.queryLatest (sm.StatusModel, info.status).get()
    comment = info.comment
    if not comment=="":
      comment = "(%s)" % comment
    msgBodyTemplate += '%s %s. Status: %s (%s)\n' % (info.time, info.positionText, status.description, comment)
    
  msgBodyTemplate += '''
  Your sincerely,
  realLifeITProject team'''
  
  msgToSupervisor = mail.EmailMessage ( sender  = 'aflinik@gmail.com',
                      subject = 'Order %d report' % so.ident )
  msgToSupervisor.to = getAuthorityEmail ( so )+ ', aflinik@gmail.com'
  msgToSupervisor.body = msgBodyTemplate % ( 'supervisor', so.ident, mp.currentDelay, lastTrackingInfos )
  msgToSupervisor.send()
  
  if sendToClients: 
    msgToClients = mail.EmailMessage ( sender  = 'aflinik@gmail.com',
                       subject = 'Order %d report' % so.ident)
    msgToClients.to = self.ClientsEmail ( so )
    msgToClients.body = msgBodyTemplate % ( 'customer', so.ident, mp.currentDelay, lastTrackingInfos )
    msgToClients.send()
